package com.youi.web;

import com.youi.exception.BusinessException;
import com.youi.manage.HttpRequestManage;
import com.youi.third.ali.oss.OSSUtil;
import com.youi.util.CommonInfoUtil;
import com.youi.util.FileUploadUtil;
import com.youi.util.JsonUtil;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

/**
 * 文件上传控制层
 * @author erdong.Chan
 *
 */
@Controller
public class UploadFileController extends HttpRequestManage {
	
	@Bean(name = "multipartResolver")
	public CommonsMultipartResolver getCommonsMultipartResolver() {
	    CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
	    multipartResolver.setMaxUploadSize(20971520);   
	    multipartResolver.setMaxInMemorySize(1048576);
	    return multipartResolver;
	}
	
	/**
     * 上传文件到oss
     * @return
     */
     @ResponseBody
     @RequestMapping("fileUploadToOss")
     public String fileUploadToOss(@RequestParam(value = "info_file") MultipartFile files,HttpServletRequest request, HttpServletResponse response,Integer width,Integer height,Integer comRate,Integer mark,ModelMap modelMap,String realpath,String url) throws IOException{			
     	try {
     		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
     	    CommonsMultipartFile multipartFile = (CommonsMultipartFile) multipartRequest.getFile("info_file");
     		String fileName = multipartFile.getOriginalFilename();// getOriginalFilename() 获取上传文件的名字
     		InputStream inStream = multipartFile.getInputStream();
     		byte[]	data = readInputStream(inStream);				
     		url=OSSUtil.upload(data, getFileType(fileName));
     	    System.out.println("url============"+url);
     		modelMap.put("url", url);
     	    modelMap.put(CommonInfoUtil.JSONCODE, CommonInfoUtil.SUCCESS);
     	    modelMap.put(CommonInfoUtil.JSONMSG, "操作成功");
     	} catch (Exception e) {
     		url="error";
     		System.err.println(e);
     		modelMap.put(CommonInfoUtil.JSONMSG, CommonInfoUtil.ERROR);
     		 modelMap.put(CommonInfoUtil.JSONMSG, "操作失败");
     	}			
     	return JsonUtil.toJson(modelMap);
     }

	/**
	 * 根据指定的图片尺寸上传图片到oss
	 * @return
	 */
	@ResponseBody
	@RequestMapping("picUploadToOss")
	public String picUploadToOss(@RequestParam(value = "info_file") MultipartFile files,HttpServletRequest request, HttpServletResponse response,ModelMap modelMap) throws BusinessException, ParseException,IOException{
		try {
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			CommonsMultipartFile multipartFile = (CommonsMultipartFile) multipartRequest.getFile("info_file");
			String fileName = multipartFile.getOriginalFilename();// getOriginalFilename() 获取上传文件的名字

			BufferedImage bi = ImageIO.read(files.getInputStream());
			if(bi == null){
				modelMap.put(CommonInfoUtil.JSONMSG, "请上传图片");
				modelMap.put(CommonInfoUtil.JSONCODE, CommonInfoUtil.ERROR);
				return JsonUtil.toJson(modelMap);
			}
			Integer width = optInteger("width",request);
			if(width==null){
				modelMap.put(CommonInfoUtil.JSONMSG, "缺少参数：width");
				modelMap.put(CommonInfoUtil.JSONCODE, CommonInfoUtil.ERROR);
				return JsonUtil.toJson(modelMap);
			}
			Integer height = optInteger("height",request);
			if(height==null){
				modelMap.put(CommonInfoUtil.JSONMSG, "缺少参数：height");
				modelMap.put(CommonInfoUtil.JSONCODE, CommonInfoUtil.ERROR);
				return JsonUtil.toJson(modelMap);
			}
//			if(!(width>=bi.getWidth() && height>=bi.getHeight())){
//				modelMap.put(CommonInfoUtil.JSONMSG, "上传的图片不符合规格要求");
//				modelMap.put(CommonInfoUtil.JSONCODE, CommonInfoUtil.ERROR);
//				return JsonUtil.toJson(modelMap);
//			}
			InputStream inStream = multipartFile.getInputStream();
			byte[]	data = readInputStream(inStream);
			String url=OSSUtil.upload(data, getFileType(fileName));
			modelMap.put("url", url);
			modelMap.put(CommonInfoUtil.JSONCODE, CommonInfoUtil.SUCCESS);
			modelMap.put(CommonInfoUtil.JSONMSG, "操作成功");
		} catch (Exception e) {
			String url="error";
			System.err.println(e);
			modelMap.put(CommonInfoUtil.JSONCODE, CommonInfoUtil.ERROR);
			modelMap.put(CommonInfoUtil.JSONMSG, "操作失败");
		}
		return JsonUtil.toJson(modelMap);
	}

     
	/**
	 * 文件上传
	 * @param files
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping("fileUpload")
	public void fileUpload(@RequestParam(value = "info_file") MultipartFile files,HttpServletRequest request, HttpServletResponse response) throws IOException{
		response.setContentType("text/html;charset=UTF-8");
		String url="";
		try {
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		    CommonsMultipartFile multipartFile = (CommonsMultipartFile) multipartRequest.getFile("info_file");
			String fileName = multipartFile.getOriginalFilename();
			if (checkFileName(fileName)) {
				String returnUrlStr=FileUploadUtil.fileUpload(request.getSession().getServletContext().getRealPath("/"), fileName, multipartFile.getBytes());
				String requestUrl=request.getRequestURL().toString();
				requestUrl=requestUrl.substring(0, requestUrl.lastIndexOf("/"));
				url=requestUrl+"/"+returnUrlStr;
			}
		} catch (Exception e) {
			url="error";
			//System.err.println(e);
			e.printStackTrace();
		}
		System.err.println(url);
		response.getWriter().write(url);
	} 
	
	/**
	 * 上传文件并得到大小
	 * @param files
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@ResponseBody
	@RequestMapping("fileUploadAndGetSize")
	public String fileUploadAndGetSize(@RequestParam(value = "info_file") MultipartFile files,
            HttpServletRequest request, HttpServletResponse response,ModelMap modelMap) throws IOException{
		response.setContentType("text/html;charset=UTF-8");
		String url="";
		try {
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		    CommonsMultipartFile multipartFile = (CommonsMultipartFile) multipartRequest.getFile("info_file");
			String fileName = multipartFile.getOriginalFilename();
			if (checkFileName(fileName)) {
				FileUploadUtil.fileUpload(modelMap,request.getSession().getServletContext().getRealPath("/"), fileName, multipartFile.getBytes());
				String returnUrlStr=(String) modelMap.get("url");
				String requestUrl=request.getRequestURL().toString();
				requestUrl=requestUrl.substring(0, requestUrl.lastIndexOf("/"));
				url=requestUrl+"/"+returnUrlStr;
				modelMap.put("url", url);
				modelMap.put(CommonInfoUtil.JSONMSG, CommonInfoUtil.SUCCESS);//1
			    System.out.println("fielurl============"+url);
			}
		} catch (Exception e) {
			modelMap.put(CommonInfoUtil.JSONMSG, CommonInfoUtil.ERROR);//-1
		}
		return JsonUtil.toJson(modelMap);
	} 
	
	/**
	 * 图片压缩上传 返回text
	 * @param files
	 * @param request
	 * @param response
	 * @param width
	 * @param height
	 * @param comRate
	 * @throws IOException
	 */
	@RequestMapping("compressionImgUpload")
	public void compressionImgUpload(@RequestParam(value = "info_file") MultipartFile files,HttpServletRequest request, HttpServletResponse response,Integer width,Integer height,Integer comRate,Integer mark) throws IOException{
		response.setContentType("text/html;charset=UTF-8");
		String url="";
		try {
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		    CommonsMultipartFile multipartFile = (CommonsMultipartFile) multipartRequest.getFile("info_file");
			String fileName = multipartFile.getOriginalFilename();
			if (checkFileName(fileName)) {
				String returnUrlStr=FileUploadUtil.imgUpload(request.getSession().getServletContext().getRealPath("/"), fileName, multipartFile.getInputStream(), width, height,comRate,mark);
				String requestUrl=request.getRequestURL().toString();
				requestUrl=requestUrl.substring(0, requestUrl.lastIndexOf("/"));
				url=requestUrl+"/"+returnUrlStr;
			    System.out.println("fielurl============"+url);
			}
		} catch (Exception e) {
			url="error";
			System.err.println(e);
		}
		response.getWriter().write(url);
	} 
	
	/**
	 * 压缩图片上传 返回json
	 * @param files
	 * @param request
	 * @param response
	 * @param width
	 * @param height
	 * @param comRate
	 * @return
	 * @throws IOException
	 */
	@ResponseBody
	@RequestMapping("webCompressionImgUpload")
	public String webCompressionImgUpload(@RequestParam(value = "info_file") MultipartFile files,HttpServletRequest request, HttpServletResponse response,Integer width,Integer height,Integer comRate,Integer mark,ModelMap modelMap,String url) throws IOException{
		try {			
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		    CommonsMultipartFile multipartFile = (CommonsMultipartFile) multipartRequest.getFile("info_file");
			String fileName = multipartFile.getOriginalFilename();// getOriginalFilename() 获取上传文件的名字
			if (checkFileName(fileName)) {
				String returnUrlStr=FileUploadUtil.imgUpload(request.getSession().getServletContext().getRealPath("/"), fileName, multipartFile.getInputStream(), width, height,comRate,mark);
				String requestUrl=request.getRequestURL().toString();
				requestUrl=requestUrl.substring(0, requestUrl.lastIndexOf("/"));
				url=requestUrl+"/"+returnUrlStr;
			    System.out.println("url============"+url);
			    modelMap.put("url", url);
			    modelMap.put(CommonInfoUtil.JSONMSG, CommonInfoUtil.SUCCESS);
			}else {
				modelMap.put(CommonInfoUtil.JSONMSG, CommonInfoUtil.NOPERMISSIONS);//-6
			}
		} catch (Exception e) {
			url="error";
			System.err.println(e);
			modelMap.put(CommonInfoUtil.JSONMSG, CommonInfoUtil.ERROR);
		}
		return JsonUtil.toJson(modelMap);
	} 
	
	/**
	 *网络连接保存图片 
	 */
	@ResponseBody
	@RequestMapping("imageUpload")
	public String imageUpload(HttpServletRequest request, HttpServletResponse response,ModelMap modelMap,String url,String urlPath) throws IOException{
		try {	
			  	URL wxUrl = new URL(urlPath);  
		        //打开链接  
		        HttpURLConnection conn = (HttpURLConnection)wxUrl.openConnection();  		      
		        //通过输入流获取图片数据  
		        InputStream inStream = conn.getInputStream();  
		        //得到图片的二进制数据，以二进制封装得到数据，具有通用性  
		        byte[] data = readInputStream(inStream);  
		        String fileType = urlPath.substring(urlPath.lastIndexOf(".")+1);				
				String formatTime=new SimpleDateFormat("ddHHmmss").format(new Date());
				String fileName=formatTime+getRandom()+"."+fileType;				
				String returnUrlStr=FileUploadUtil.fileUpload(request.getSession().getServletContext().getRealPath("/"), fileName, data);
				String requestUrl=request.getRequestURL().toString();
				requestUrl=requestUrl.substring(0, requestUrl.lastIndexOf("/"));
				url=requestUrl+"/"+returnUrlStr;
			    System.out.println("url============"+url);
			    modelMap.put("url", url);
			    modelMap.put(CommonInfoUtil.JSONMSG, CommonInfoUtil.SUCCESS);
		} catch (Exception e) {
			url="error";
			System.err.println(e);
			modelMap.put(CommonInfoUtil.JSONMSG, CommonInfoUtil.ERROR);
		}
		return JsonUtil.toJson(modelMap);
	} 

    /**
     * 小程序上传图片
     * @return
     */
		@ResponseBody
		@RequestMapping("miniAppUploadImg")
		public String miniAppUploadImg(@RequestParam(value = "info_file") MultipartFile files,HttpServletRequest request, HttpServletResponse response,Integer width,Integer height,Integer comRate,Integer mark,ModelMap modelMap,String realpath,String url) throws IOException{			
			try {
				MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			    CommonsMultipartFile multipartFile = (CommonsMultipartFile) multipartRequest.getFile("info_file");
				String fileName = multipartFile.getOriginalFilename();// getOriginalFilename() 获取上传文件的名字
				InputStream inStream = multipartFile.getInputStream();
				byte[]	data = readInputStream(inStream);				
				String returnUrlStr=FileUploadUtil.fileUpload(request.getSession().getServletContext().getRealPath("/"), fileName,data);
				String requestUrl=request.getRequestURL().toString();
				requestUrl=requestUrl.substring(0, requestUrl.lastIndexOf("/"));
				url=requestUrl+"/"+returnUrlStr;
			    System.out.println("url============"+url);
				modelMap.put("url", url);
			    modelMap.put(CommonInfoUtil.JSONMSG, CommonInfoUtil.SUCCESS);				
			} catch (Exception e) {
				url="error";
				System.err.println(e);
				modelMap.put(CommonInfoUtil.JSONMSG, CommonInfoUtil.ERROR);
			}			
			return JsonUtil.toJson(modelMap);
		} 
		
	public  static int getRandom(){
		Random random=new Random();
		return random.nextInt(99999);
	}

	/**
	 * 编辑器上传图片
	 * @param files
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping("filesUpload")
	public void filesUpload(@RequestParam(value = "files") MultipartFile files,
            HttpServletRequest request, HttpServletResponse response) throws IOException{
		response.setContentType("text/html;charset=UTF-8");
		String url="";
		try {
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		    CommonsMultipartFile multipartFile = (CommonsMultipartFile) multipartRequest.getFile("files");
			String fileName = multipartFile.getOriginalFilename();
			if (checkFileName(fileName)) {
				String returnUrlStr=FileUploadUtil.fileUpload(request.getSession().getServletContext().getRealPath("/"), fileName, multipartFile.getBytes());
				String requestUrl=request.getRequestURL().toString();
				requestUrl=requestUrl.substring(0, requestUrl.lastIndexOf("/"));
				url=requestUrl+"/"+returnUrlStr;
			    System.out.println("fielurl============"+url);
			}
		} catch (Exception e) {
			url="error";
			System.err.println(e);
		}
		response.getWriter().write(url);
	} 
	
	/**
	 * app上传图片
	 * @param files
	 * @param request
	 * @param response
	 * @param width
	 * @param height
	 * @param modelMap
	 * @return
	 * @throws IOException
	 */
	@ResponseBody
	@RequestMapping("appCompressionImgUpload")
	public String appCompressionImgUpload(@RequestParam(value = "info_file") MultipartFile files,
            HttpServletRequest request, HttpServletResponse response,Integer width,Integer height,ModelMap modelMap,Integer comRate,Integer mark) throws IOException{
		response.setContentType("text/html;charset=UTF-8");
		String url="";
		try {
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		    CommonsMultipartFile multipartFile = (CommonsMultipartFile) multipartRequest.getFile("info_file");
		    String fileName = multipartFile.getOriginalFilename();
		    if (checkFileName(fileName)) {
		    	String returnUrlStr=FileUploadUtil.imgUpload(request.getSession().getServletContext().getRealPath("/"), fileName, multipartFile.getInputStream(), width, height,comRate,mark);
				String requestUrl=request.getRequestURL().toString();
				requestUrl=requestUrl.substring(0, requestUrl.lastIndexOf("/"));
				url=requestUrl+"/"+returnUrlStr;
				modelMap.put(CommonInfoUtil.JSONMSG, CommonInfoUtil.SUCCESS);
				modelMap.put("url", url);
			    System.out.println("fielurl============"+url);
			}
		} catch (Exception e) {
			url="error";
			System.err.println(e);
			modelMap.put(CommonInfoUtil.JSONMSG, CommonInfoUtil.ERROR);
		}
		return JsonUtil.toJson(modelMap);
	} 
	
	/**
	 * 上传base64图片
	 * @param request
	 * @param img
	 * @return
	 */
	@ResponseBody
	@RequestMapping("uploadImgByBase64")
	public String uploadImgByBase64(ModelMap modelMap,HttpServletRequest request,String img,Integer mark){
		if (img!=null&&img.length()>0) {
			String url=FileUploadUtil.uploadBase64Img(request, img,mark);
			if (url!=null&&url.length()>0) {
				modelMap.put("url", url);
				modelMap.put(CommonInfoUtil.JSONMSG, CommonInfoUtil.SUCCESS);
			}else {
				modelMap.put(CommonInfoUtil.JSONMSG, CommonInfoUtil.NULLDATA);
			}
		}else {
			modelMap.put(CommonInfoUtil.JSONMSG, CommonInfoUtil.PARAMERROR);
		}
		return JsonUtil.toJson(modelMap);
	}
	
	  
	/**
	 * 上传文件类型匹配
	 * @param fileName
	 * @return
	 */
	private boolean checkFileName(String fileName){
		if (fileName.contains(".jpg")||fileName.contains(".JPG")||fileName.contains(".BMP")||fileName.contains(".bmp")||fileName.contains(".png")||fileName.contains(".PNG")||fileName.contains(".mp3")||fileName.contains(".MP3")||fileName.contains(".mp4")||fileName.contains(".MP4")||fileName.contains(".GIF")||fileName.contains(".gif")) {
			return true;
		}
		return false;
	}
	
	/**
	 * 获取文件类型
	 * @param fileName
	 * @return
	 */
	private String getFileType(String fileName) {
		if (fileName!=null) {
			String filetype = fileName.substring(fileName.lastIndexOf("."),fileName.length());
			return filetype;
		}
		return fileName;
	}
	
	  private byte[] readInputStream(InputStream inStream) throws Exception{  
	        ByteArrayOutputStream outStream = new ByteArrayOutputStream();  
	        //创建一个Buffer字符串  
	        byte[] buffer = new byte[1024];  
	        //每次读取的字符串长度，如果为-1，代表全部读取完毕  
	        int len = 0;  
	        //使用一个输入流从buffer里把数据读取出来  
	        while( (len=inStream.read(buffer)) != -1 ){  
	            //用输出流往buffer里写入数据，中间参数代表从哪个位置开始读，len代表读取的长度  
	            outStream.write(buffer, 0, len);  
	        }  
	        //关闭输入流  
	        inStream.close();  
	        //把outStream里的数据写入内存  
	        return outStream.toByteArray();  
	    }  
}
